import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components"
import { Row ,Col, Card, Switch, Button, Dropdown, Space, FormInstance, message, Modal} from "antd"
import {ArrowUpOutlined, DeleteOutlined, DownOutlined, PlusOutlined} from '@ant-design/icons';
import { changeUserStatus, getUserList } from "@/services/system/user";

import { useState ,useEffect,useRef} from "react";
import DeptTree from "./components/DeptTree";
import { getDictValueEnum } from "@/services/system/dict";
import { useAccess } from "@umijs/max";
const UserTableList : React.FC=()=>{
    let [selectDeptId,setSelectDeptId]=useState<string>('0');
    const [statusOptions,setStatusOptions]=useState<any>([]);
    const actionRef=useRef<ActionType>();
    const formTableRef=useRef<FormInstance>();
    const [selectRows,setSelectedRows]=useState<API.System.User[]>([]);
    const [messageApi,contextHolder]=message.useMessage();
    const access=useAccess();
    useEffect( ()=>{
        getDictValueEnum('sys_normal_disable').then((res)=>{
            setStatusOptions(res);
        })
    },[]);
    useEffect(()=>{
        if(selectDeptId){
            formTableRef.current?.submit();
        }
    },[selectDeptId])
    const onSelectByDept=(selectedKeys:string)=>{
        console.log(selectedKeys);
        setSelectDeptId(selectedKeys);
        // if(actionRef.current){
        //     formTableRef.current?.submit();
        // }
    }
    const showChangeStatusConfirm=(record:API.System.User)=>{
        console.log(record);
        let statusText=record.status=='1'?"启用":"停用";
        let newStatus=record.status=='1'?'0':'1';
        Modal.confirm({
            title:`确定要${statusText}${record.userName}用户吗？`,
            onOk:async()=>{
                let result=await changeUserStatus(record.userId,newStatus);
                if(result.code==200){
                    messageApi.open({
                        type:"success",
                        content:"更新成功!"
                    });
                    actionRef.current?.reload();
                }
                else{
                    messageApi.open({
                        type:"error",
                        content:result.msg
                    })
                }
            }
        })
    }
    const column:ProColumns<API.System.User>[]=[{
        title:<div>用户编号</div>,
        valueType:"text",
        dataIndex:"deptId"
    },{
        title:<div>用户账号</div>,
        valueType:"text",
        dataIndex:"userName"
    },{
        title:<div>用户昵称</div>,
        valueType:"text",
        dataIndex:"nickName"
    },{
        title:<div>部门</div>,
        valueType:"text",
        hideInSearch:true,
        dataIndex:['dept','deptName']
    },{
        title:<div>手机号码</div>,
        valueType:"text",
        dataIndex:"phonenumber"
    },{
        title:<div>账号状态</div>,
        valueType:"select",
        valueEnum:statusOptions,
        render:(_,record)=>{
            return <Switch defaultChecked checkedChildren='正常' 
            onClick={()=>showChangeStatusConfirm(record)}
            unCheckedChildren='停用' checked={record.status==='0'}/>
        },
        dataIndex:"status"
    },{
        title:<div>操作</div>,
        valueType:"option",
        dataIndex:"option",
        render:(_,record)=>{
            return [
                <Button type="link">编辑</Button>,
                <Button danger type="link">删除</Button>,
                <Dropdown key={'more'} menu={{items:[
                    {label:<div>密码重置</div>,key:"reset"},
                    {label:<div>分配角色</div>,key:"authRole"}
                ]}}><a>
                        <Space><DownOutlined/>更多</Space>
                    </a></Dropdown>,
            ]
        }
    },]
    return <PageContainer>
        {contextHolder}
        {/* [水平间距,垂直间距] */}
        <Row gutter={[16,24]}>
            <Col lg={6} md={24}>
                <Card>
                    <DeptTree onSelectByDept={onSelectByDept}/>
                </Card>
            </Col>
            <Col md={24} lg={18}>
                <ProTable<API.System.User>
                    headerTitle={<div>查询表格</div>}
                    search={{labelWidth:120}}
                    actionRef={actionRef}
                    formRef={formTableRef}
                    rowKey={'userId'}
                    key={'userList'}
                    request={async(params)=>{
                        // 第一个参数中一定会有 pageSize 和  current
                        console.log(params);
                        let result=await getUserList({...params,deptId:selectDeptId} as API.System.UserListParams);  
                        return {data:result.rows,success:true,total:result.total};
                    }}
                    columns={column}
                    toolBarRender={(action)=>{
                        return [
                            <Button icon={<PlusOutlined/>} type="primary" disabled={!access.hasPerms('system:user:add')}>新建</Button>,
                            <Button icon={<DeleteOutlined/>} type="primary" danger
                            disabled={!access.hasPerms('system:user:remove')||selectRows.length==0}
                            >删除</Button>,
                            <Button icon={<ArrowUpOutlined />} type="primary">导出</Button>
                        ]
                    }}
                    rowSelection={{
                        onChange:(_,selectedRows)=>{
                            // console.log('selectedRows',selectedRows);
                            setSelectedRows(selectedRows);
                        }
                    }} 
                    />
            </Col>
        </Row>
        </PageContainer>
}
export default UserTableList;